﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

using SManaModel.models;

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace SManaApi.Services
{
    public class JwtService
    {
        public TokenConfig _tokenConfig { get; set; }

        public JwtService(TokenConfig tokenConfig)
        {
            _tokenConfig = tokenConfig;
        }

        public IEnumerable<Claim>? GetCliams(HttpContext context)
        {
            return context.User.Claims;
        }

        public string? GetCliam(HttpContext context, string name)
        {
            var val = GetCliams(context)?.Where(x => x.Type == name).FirstOrDefault()?.Value;
            return val;
        }

        public int GetId(HttpContext context)
        {
            return int.TryParse(GetCliam(context, "id"),out var id) ? id: 0;
        }

        public string? GetType(HttpContext context)
        {
            return GetCliam(context, "type");
        }

        public bool IsExpired(HttpContext context)
        {
            throw new NotImplementedException();
        }


        public string SetToken(Microsoft.AspNetCore.Http.HttpContext context, params Claim[] claims)
        {
            var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_tokenConfig.Secret.Trim()));
            var jwtSecurityToken = new JwtSecurityToken(
                issuer: _tokenConfig.Issuer,
                audience: _tokenConfig.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddMinutes(_tokenConfig.AccessExpiration),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            //context.Response.Headers.Add("Token", new Microsoft.Extensions.Primitives.StringValues(token));
            return token;
        }
    }
}
